package com.blunka.framework.client.ui;

import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;

import org.apache.commons.lang3.StringUtils;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;

import com.blunka.framework.client.utils.DesignUtils;

/**
 * 系统日志窗体
 *
 * @author Administrator
 *
 */
@SuppressWarnings("serial")
public class LoggerPanel extends JPanel {

	private static LoggerPanel panel = new LoggerPanel();

	private JTabbedPane tabPanel;

	private RSyntaxTextArea textPanel;

	private JScrollPane scrollPanel;

	private long lastTimeFileSize = 0; // 上次文件大小

	private RandomAccessFile randomFile;

	public static LoggerPanel newInstance() {
		return panel;
	}

	private LoggerPanel() {
		initPanel();
		seekLogLast();
		initMonitorLog();
	}

	private void initPanel() {
		setLayout(new BorderLayout());
		textPanel = new RSyntaxTextArea();
		textPanel.setSyntaxEditingStyle(RSyntaxTextArea.SYNTAX_STYLE_JAVA);
		// textPanel.setEditable(false);
		tabPanel = new JTabbedPane();
		scrollPanel = new JScrollPane(textPanel);
		tabPanel.addTab("系统日志", scrollPanel);
		add(tabPanel, BorderLayout.CENTER);

	}

	/**
	 * 初始化监控日志
	 */
	private void initMonitorLog() {
		try {
			final File tmpLogFile = new File(DesignUtils.getDir() + "/logs/Designer.log");
			if (tmpLogFile.exists()) {
				tmpLogFile.createNewFile();
			}
			realtimeShowLog(tmpLogFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 默认直接文件定位到最后
	 * @param logFile
	 * @throws IOException
	 */
	private void seekLogLast(){

		try {
			final File tmpLogFile = new File(DesignUtils.getDir() + "/logs/Designer.log");
			randomFile = new RandomAccessFile(tmpLogFile, "rw");
			// 获得变化部分的
			/*randomFile.seek(lastTimeFileSize);
			String tmp = "";
			while ((tmp = randomFile.readLine()) != null) {
				String str = new String(tmp.getBytes("ISO8859-1"));
				String times = str.substring(0, str.indexOf(","));
				// 只显示当前时间之后的日志内容
				if (times.compareTo(CURRENTTIME) > 0) {
					logMsg(str);
				}
			}*/
			lastTimeFileSize = randomFile.length();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 实时输出日志信息
	 *
	 * @param logFile
	 *            日志文件
	 * @throws IOException
	 */
	private void realtimeShowLog(File logFile) throws IOException {
		randomFile = new RandomAccessFile(logFile, "rw");
		// 启动一个线程每10秒钟读取新增的日志信息
		ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
		exec.scheduleWithFixedDelay(new Runnable() {
			public void run() {
				try {
					// 获得变化部分的
					randomFile.seek(lastTimeFileSize);
					String tmp = "";
					while ((tmp = randomFile.readLine()) != null) {
						String str = new String(tmp.getBytes("ISO8859-1"));
						//String times = str.substring(0, str.indexOf(","));
						// 只显示当前时间之后的日志内容
						//if (times.compareTo(CURRENTTIME) > 0) {
							logMsg(str);
						//}
					}
					lastTimeFileSize = randomFile.length();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}, 0, 1, TimeUnit.SECONDS);
	}

	/**
	 * 输入日志到控制台
	 *
	 * @param msg
	 */
	public void logMsg(String msg) {
		textPanel.setCaretPosition(textPanel.getText().length());
		if (StringUtils.isEmpty(textPanel.getText())) {
			textPanel.append(msg);
		} else {
			textPanel.append("\n" + msg);
		}
		textPanel.setCaretPosition(textPanel.getText().length());
	}
}
